package com.rightsidetech.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rightsidetech.commom.base.DelReq;
import com.rightsidetech.commom.base.ResponseData;
import com.rightsidetech.commom.enums.CodeIdEnum;
import com.rightsidetech.commom.utils.BeanValidator;
import com.rightsidetech.system.dtos.request.adverts.*;
import com.rightsidetech.system.dtos.response.adverts.AppBannerResp;
import com.rightsidetech.system.dtos.response.adverts.BannerPageResp;
import com.rightsidetech.system.entity.adverts.SysAdvertsBanner;
import com.rightsidetech.system.mapper.SysAdvertsBannerMapper;
import com.rightsidetech.system.service.SysAdvertsBannerService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service("sysAdvertsBannerService")
public class SysAdvertsBannerServiceImpl implements SysAdvertsBannerService {

    @Resource
    private SysAdvertsBannerMapper sysAdvertsBannerMapper;

    @Override
    public ResponseData saveBanner(BannerSaveReq req,String createrName,String jumpName) {
        Date startDate = req.getStartDate();
        Date endDate = req.getEndDate();
        if(endDate.compareTo(startDate) <= 0){
            return ResponseData.fail("发布结束时间不可以小于或等于开始时间");
        }
        if(getYesterday().compareTo(startDate) > 0){
            return ResponseData.fail("开始时间不可小于今天");
        }
        Long count = sysAdvertsBannerMapper.selectCountByTopicName(req.getTopicName());
        if(count > 0){
            return ResponseData.fail("主题已经存在");
        }
        SysAdvertsBanner record = new SysAdvertsBanner();
        record.setTopicName(req.getTopicName());
        record.setBannerType(req.getBannerType());
        record.setJumpId(req.getJumpId());
        record.setPicture(req.getPicture());
        record.setJumpName(jumpName);
        record.setPlatform(req.getPlatform());
        record.setStartDate(req.getStartDate());
        record.setEndDate(parseTime(req.getEndDate()));
        record.setCreaterName(createrName);
        record.setCreatedAt(new Date());
        SysAdvertsBanner sysAdvertsBanner = sysAdvertsBannerMapper.selectByBannerSort();
        if(ObjectUtil.isEmpty(sysAdvertsBanner) || sysAdvertsBanner.getBannerSort() == null){
            record.setBannerSort(1L);
        }else {
            record.setBannerSort(sysAdvertsBanner.getBannerSort() + 1);
        }
        if (sysAdvertsBannerMapper.insertSelective(record) <= 0) {
            return ResponseData.fail("添加失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<PageInfo<BannerPageResp>> pageBanner(BannerPageReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        PageHelper.startPage(req.getPageNo(),req.getPageSize());
        List<BannerPageResp> result = sysAdvertsBannerMapper.selectPageList(req);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (BannerPageResp resp : result) {
            Date startDa = resp.getStartDa();
            Date endDa = resp.getEndDa();
            resp.setStartDate(format.format(startDa));
            resp.setEndDate(format.format(endDa));
            resp.setStatus((byte) (isEffectiveDate(new Date(),startDa,endDa) ? 0 : 1));
        }
        return ResponseData.success(new PageInfo<>(result));
    }

    private boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);
        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);
        Calendar end = Calendar.getInstance();
        end.setTime(endTime);
        if(date.after(begin) && date.before(end)){
            return true;
        }
        return false;
    }

    @Override
    public ResponseData update(BannerUpReq req,String jumpName) {
        Date startDate = req.getStartDate();
        Date endDate = req.getEndDate();
        SysAdvertsBanner advertsBanner = sysAdvertsBannerMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(advertsBanner) || advertsBanner.getIsDeleted() == 1){
            return ResponseData.fail("未找到要更新的数据");
        }
        if(!startDate.equals(advertsBanner.getStartDate()) || !endDate.equals(advertsBanner.getEndDate())){
            if(endDate.compareTo(startDate) <= 0){
                return ResponseData.fail("发布结束时间不可以小于或等于开始时间");
            }
            if(getYesterday().compareTo(startDate) > 0){
                return ResponseData.fail("开始时间不可小于今天");
            }
        }
        if(!req.getTopicName().equals(advertsBanner.getTopicName())){
            Long count = sysAdvertsBannerMapper.selectCountByTopicName(req.getTopicName());
            if(count > 0){
                return ResponseData.fail("主题已经存在");
            }
        }
        advertsBanner.setTopicName(req.getTopicName());
        advertsBanner.setBannerType(req.getBannerType());
        advertsBanner.setJumpId(req.getJumpId());
        advertsBanner.setJumpName(jumpName);
        advertsBanner.setPicture(req.getPicture());
        advertsBanner.setPlatform(req.getPlatform());
        advertsBanner.setStartDate(req.getStartDate());
        advertsBanner.setEndDate(parseTime(req.getEndDate()));
        advertsBanner.setUpdatedAt(new Date());
        if (sysAdvertsBannerMapper.updateByPrimaryKey(advertsBanner) <= 0) {
            return ResponseData.fail("修改失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData isClose(CloseLoadReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAdvertsBanner sysAdvertsBanner = sysAdvertsBannerMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(sysAdvertsBanner) || sysAdvertsBanner.getIsDeleted() == 1) {
            return ResponseData.fail("没有找到要操作的数据");
        }
        sysAdvertsBanner = new SysAdvertsBanner();
        sysAdvertsBanner.setId(req.getId());
        sysAdvertsBanner.setIsClose(req.getIsClose());
        if (sysAdvertsBannerMapper.updateByPrimaryKeySelective(sysAdvertsBanner) <= 0) {
            return ResponseData.fail("操作失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData del(DelReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        SysAdvertsBanner sysAdvertsBanner = sysAdvertsBannerMapper.selectByPrimaryKey(req.getId());
        if(ObjectUtil.isEmpty(sysAdvertsBanner) || sysAdvertsBanner.getIsDeleted() == 1) {
            return ResponseData.fail("没有找到要操作的数据");
        }
        sysAdvertsBanner = new SysAdvertsBanner();
        sysAdvertsBanner.setId(req.getId());
        sysAdvertsBanner.setIsDeleted((byte)1);
        if (sysAdvertsBannerMapper.updateByPrimaryKeySelective(sysAdvertsBanner) <= 0) {
            return ResponseData.fail("操作失败");
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public ResponseData<List<AppBannerResp>> appBanner(List<Long> commodityIds) {
        List<AppBannerResp> result = sysAdvertsBannerMapper.selectAppletsList(commodityIds);
        return ResponseData.success(result);
    }

    @Override
    public ResponseData<List<AppBannerResp>> appBanner(Byte platform) {
        List<AppBannerResp> result = sysAdvertsBannerMapper.selectAppList(platform);
        return ResponseData.success(result);
    }

    @Override
    public ResponseData sortBanner(BannerSortReq req) {
        ConstraintViolation validate = BeanValidator.validate(req);
        if (validate != null) {
            return new ResponseData(CodeIdEnum.ParameterMalformed.getValue(), validate.getMessage());
        }
        List<Long> ids = req.getId();
        List<Long> sorts = req.getSort();
        if(ids.size() != sorts.size()){
            return ResponseData.fail(CodeIdEnum.ParameterMalformed.getValue(),"id与排序数量不一致");
        }
        List<SysAdvertsBanner> banners = sysAdvertsBannerMapper.selectByIds(ids);
        if(banners.size() != ids.size()){
            return ResponseData.fail("有未找到banner的id");
        }
        for (int i = 0; i < banners.size(); i++) {
            Long id = ids.get(i);
            Long sort = sorts.get(i);
            if(Long.valueOf(0).equals(sort) || sort < 0){
                sort = null;
            }
            int count = sysAdvertsBannerMapper.updateSortById(id, sort);
            if (count <= 0) {
                return ResponseData.fail("操作失败");
            }
        }
        return ResponseData.success(CodeIdEnum.Success);
    }

    @Override
    public List<BannerPageResp> selectById(List<Long> ids) {
        List<BannerPageResp> resps = new ArrayList<>();
        ids.forEach(id ->{
            resps.add(sysAdvertsBannerMapper.selectById(id));
        });
        return resps;
    }

    private Date getYesterday(){
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH) - 1,23,59,59);
        return calendar.getTime();
    }

    public Date parseTime(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH),23,59,59);
        return calendar.getTime();
    }

    @Override
    public ResponseData<List<BannerPageResp>> list(BannerPageReq req) {
        List<BannerPageResp> result = sysAdvertsBannerMapper.selectList(req);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        for (BannerPageResp resp : result) {
            Date startDa = resp.getStartDa();
            Date endDa = resp.getEndDa();
            resp.setStartDate(format.format(startDa));
            resp.setEndDate(format.format(endDa));
            resp.setStatus((byte) (isEffectiveDate(new Date(),startDa,endDa) ? 0 : 1));
        }
        return ResponseData.success(result);
    }
}
